package beanstao.util.j2ee.tidy;

import java.util.Map;

import org.dom4j.Element;

import beanstao.util.reflect.Mirror;
import beanstao.util.setting.Setting;

import com.google.common.collect.Maps;

public class TidySetting extends Setting<Element>
{

	/**
	 * @return 返回本类型的单建实例(延迟加载,并对多线程进行处理)
	 */
	public static TidySetting ME()
	{
		return Single.instance;
	}

	/**
	 * 为单建模式设计的内部静态类型
	 */
	static class Single
	{
		/**
		 * 多线程锁
		 */
		static Object lock = new Object();
		static
		{
			synchronized (lock)
			{
				instance = new TidySetting();
			}
		}
		static TidySetting instance;
	}

	/**
	 * 针对单建模式,私有化本类型构造函数
	 */
	private TidySetting()
	{
	}

	@SuppressWarnings("rawtypes")
	public Map<String, ITidy> _TidyMap = Maps.newHashMap();

	@SuppressWarnings("rawtypes")
	public Map<String, ITidy> getTidyMap()
	{
		return _TidyMap;
	}

	@Override
	protected void fillSettingData(Element element)
	{
		for (Element clearSetting : element.elements())
		{
			String className = clearSetting.attributeValue("key");
			String klassname = clearSetting.attributeValue("class");
			Class<?> klass = null;
			try
			{
				klass = Class.forName(klassname);
			}
			catch (ClassNotFoundException e)
			{
				this.logDebug(klass + "未找到。");
			}
			Mirror<?> mirror = Mirror.me(klass);
			Object tidy = null;
			try
			{
				tidy = mirror.born();
			}
			catch (Exception e)
			{
				this.logDebug(tidy + "未初始化。");
			}
			if (tidy instanceof ITidy)
				_TidyMap.put(className, (ITidy<?>) tidy);
			else
				this.logWarn(tidy.getClass().getSimpleName() + "不是ITidy接口实现类型。");
		}
	}

}
